# coding=utf-8
import sys
from function_utils import Global, Common, TableRender


def ip_info():
    cmd = '''ip a | grep -w inet | awk '{print $2" "$NF}' | awk -F: '{print $1}' '''
    nets = Common.execute_cmd(cmd)[1]
    devs = {}
    max_c = 0
    for line in nets.strip().split('\n'):
        ip, dev = line.split()
        if dev in devs:
            devs[dev].append(ip)
        else:
            devs[dev] = [ip]
        max_c = max(len(devs[dev]), max_c)

    info = ['']
    for dev, ips in devs.items():
        info[0] = '%s|%s' % (info[0], dev)
        info[0] = info[0].strip('|')
        ip_len = len(ips)
        for i in range(max_c):
            if len(info) - 1 < max_c:
                info.append('-')
            ip = ips[i] if i < ip_len else ''
            info[i + 1] = '%s|%s' % (info[i + 1], ip)
            info[i + 1] = info[i + 1].replace('-|', '')

    info = TableRender('\n'.join(info))
    return info


def add_ip(itf, ips):
    cmd = '''ip a add {0} dev {1}'''.format(ips, itf)
    ret, out, err = Common.execute_cmd(cmd)
    print(out)
    print(err)


def del_ip(itf, ips):
    cmd = '''ip a del {0} dev {1}'''.format(ips, itf)
    ret, out, err = Common.execute_cmd(cmd)
    print(out)
    print(err)


def write_widgets_value(value):
    data = [
        {"MultiInfoText": value},
        {},
        {},
        {}
    ]
    Global.values_write(data)
    Global.report_info(100)


def main():
    if sys.argv[1] == 'pre':
        write_widgets_value(ip_info())
    elif sys.argv[1] == 'start':
        data = Global.values_parse(sys.argv[2])
        itf = data[2]['Entry'].strip()
        ips = data[3]['Entry'].strip()
        if data[1]['Combobox'].strip() == 'Add':
            add_ip(itf, ips)
        else:
            del_ip(itf, ips)
        write_widgets_value(ip_info())


if __name__ == '__main__':
    main()

